<?php
/**
 * Description of ProductFeed
 * Generates XML file with all products according to Google Product Feed specification
 *
 * @author Pavel Kovalyov
 */
class RCMS_Object_Product_ProductFeed
{
    /**
     * Path to view with xml template
     */
    const VIEW_PATH = '/views/scripts/backend/shopping';

    private $_model;
    private $_sitePath;
    private $_siteUrl;
    private $_view;

    public function  __construct() {
        $this->_model       = new RCMS_Object_Product_ProductModel();
        $this->_sitePath    = unserialize(Zend_Registry::get('config'))->website->website->path;
        $this->_siteUrl     = unserialize(Zend_Registry::get('config'))->website->website->url;
        $this->_view        = new Zend_View();
        //$this->_view->setScriptPath($this->_sitePath . self::VIEW_PATH);
        $this->_view->setScriptPath(APPLICATION_PATH . self::VIEW_PATH);
        $this->_view->websiteUrl = $this->_siteUrl;

    }

    /**
     * Method generates product.xml file with all products you have
     * @return nothing
     */
    public function generateFullProductXML() {
        $products       = $this->_model->selectAllProducts();
		$extendedFields = $this->_getExtendedFields();
        foreach ($products as $product) {

            $link = '';
            $page = new RCMS_Object_Page_Page($product['page_id']);
            if ($page->getId() > 0 && $page->getUrl() != '') {
                $link = $this->_siteUrl.trim($page->getUrl()).'.html';
            }

			if(!$link) {
				continue;
			}

			$productPageCreationDate = $page->getDate();
            unset ($page);

			$productGroups = $this->_model->selectGroupsForProduct($product['id']);
			$categories    = array();
			foreach ($productGroups as $key => $productGroupsData) {
				$categories[] = $productGroupsData['name'];
			}
            $data[$product['id']] = array(
				'title'                  => htmlspecialchars(RCMS_Tools_Tools::convertEncoding($product['name'])),
				'link'                   => htmlspecialchars(RCMS_Tools_Tools::convertEncoding($link)),
				'description'            => $this->_prepareDescription($product),
				'id'                     => $product['item_id'],
				'pubDate'                => ($productPageCreationDate) ? $productPageCreationDate : time(),
				'price'                  => $this->_calculatePrice($product), //$product['price'],
				'condition'              => 'new',
				'brand'                  => htmlspecialchars(RCMS_Tools_Tools::convertEncoding($product['brand'])),
				'image_link'             => $this->_siteUrl . RCMS_Tools_Tools::convertEncoding($product['photo']),
				'product_type'           => implode(',', $categories),
				'sale_due'               => ($product['sale_due']) ? date('c', strtotime($product['sale_due'])) : '',
				'mpn'                    => $product['mpn'],
				'regular_price'          => $product['old_price'],
				'featured_product'       => ($product['old_price']) ? 'y' : 'n',
				'shipping_weight'        => $product['weight'],
				'product_review_average' => $product['rating'],
				'product_options'        => str_replace(':::', ':', str_replace('###', ';', $product['options']))
            );

			foreach ($extendedFields as $extendedFieldsPerProduct) {
				if($extendedFieldsPerProduct['productId'] == $product['id']) {
					$data[$product['id']]['extendedFields'][strtolower(str_replace(' ', '_', $extendedFieldsPerProduct['name']))] = $extendedFieldsPerProduct['value'];
				}
			}

        }

        $this->_view->products = $data;

        $indexPage = new RCMS_Object_Page_PageModel();
        $select = $indexPage->getAdapter()->select()
                    ->from('page',array ('meta_description','header_title'))
                    ->where("url = 'index'");
        $header = $indexPage->getAdapter()->fetchRow($select);
        unset ($indexPage);

        $this->_view->description = htmlspecialchars($header['meta_description']);
        $this->_view->title       = htmlspecialchars($header['header_title']);

        $file = $this->_view->render('productsxml.phtml');
        RCMS_Tools_FilesystemTools::saveFile('products.xml', $file);
    }

	private function _getExtendedFields() {
		$pluginManager = new RCMS_Object_PluginManager_PluginManager(unserialize(Zend_Registry::get('config')));
		if($pluginManager->checkPluginInstalled('specs')) {
			if($pluginManager->pluginStatus('specs') == RCMS_Object_Plugin_Plugin::STAT_ENABLED) {
				$productFeedModel = new RCMS_Object_Product_ProductFeedModel();
				return $productFeedModel->fetchExtended();

			}
		}
		return array();
	}

	private function _calculatePrice($product) {
		$shoppingConfigModel = new Backend_ShoppingModel();
		$shoppingSettings = $shoppingConfigModel->selectShoppingConfig();
		$addTax = 1;
		if(isset($shoppingSettings['show-price-ati']) && $shoppingSettings['show-price-ati'] == '1' && $product['tax'] > 0) {
			$shipping = new RCMS_Object_Shipping_Shipping();
            $shippingAddress = $shipping->getShippingAddress();
            unset($shipping);

			if (!empty($shippingAddress)){
                $location = array('country'=>$shippingAddress['country'],'state'=>$shippingAddress['state']);
            } else {
                $location = array('country'=>$shoppingSettings['country'],'state'=>$shoppingSettings['state']);
                $defaultTaxRule = unserialize($shoppingSettings['default_tax_rule']);
            }
			if (!empty ($defaultTaxRule)) {
                $addTax = 1 + $defaultTaxRule['tax'][$product['tax']] / 100;
            } else {
                $taxRules = unserialize($shoppingSettings['tax-rules']);
                foreach ($taxRules as $rule) {
                    if (
                            ($rule['zone']==$location['country'] && in_array($location['state'],  explode(',', $rule['subzone']))) ||
                            (($location['state']=='' || $location['state']=='null') && in_array($location['country'],explode(',',$rule['subzone'])))
                       )
                    {
                        $addTax = 1 + $rule['tax'][$product['tax']]/100;
                        break;
                    }
                }
            }
		}
		return number_format(($product['price'] * $addTax), 2, '.', '');
	}

	private function _prepareDescription($productData) {
		$description = (isset($productData['full_description']) && $productData['full_description']) ? $productData['full_description'] : $productData['desc'];
		return htmlspecialchars(RCMS_Tools_Tools::convertEncoding($description));
	}
}